package com.aaa.system.service.impl;

import com.aaa.entity.DictData;
import com.aaa.entity.DictType;
import com.aaa.system.dao.DictDataDao;
import com.aaa.system.dao.DictTypeDao;
import com.aaa.system.service.DictDataService;
import com.aaa.vo.Result;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
/**
 * @program: his-open-parent
 * @description:
 * @author: 闫克起2
 * @create: 2023-03-21 11:13
 **/
@Service
public class DictDataServiceImpl implements DictDataService {
    @Autowired
    private DictDataDao dictDataDao;
    @Autowired
    private DictTypeDao dictTypeDao;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public Result<List<DictData>> findByType(String type) {
        try{
            String s = redisTemplate.opsForValue().get(type);
            if(StringUtils.hasText(s)){
                List<DictData> dictData = JSON.parseArray(s, DictData.class);
                return new Result<>(2000,"查询成功",dictData);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        QueryWrapper<DictData> wrapper=new QueryWrapper<>();
        wrapper.eq("dict_type",type);
        List<DictData> list = dictDataDao.selectList(wrapper);
        return new Result<>(2000,"查询成功",list);
    }


    @Override
    public Result<String> cacheAsync() {
        //查询所有数据字典类型
        QueryWrapper<DictType> wrapper=new QueryWrapper<>();
        wrapper.eq("status",0);
        List<DictType> dictTypes = dictTypeDao.selectList(wrapper);
        //查询所有数据字典的数据
        //sys_user_sex---->[男，女，未知]
        for (DictType dictType : dictTypes) {
            QueryWrapper<DictData> wrapper2=new QueryWrapper<>();
            wrapper2.eq("status",0);
            wrapper2.eq("dict_type",dictType.getDictType());
            List<DictData> dictDatas = dictDataDao.selectList(wrapper2);
            redisTemplate.opsForValue().set(dictType.getDictType(), JSON.toJSONString(dictDatas));
        }
        return new Result<String>(2000,"缓存同步成功");
    }
}
